/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bpmlab.shift.config;

import bpmlab.shift.dao.JpaUtil;
import bpmlab.shift.entity.Aplicacao;
import bpmlab.shift.entity.Cardapio;
import bpmlab.shift.entity.Equipamento;
import bpmlab.shift.entity.Item;
import bpmlab.shift.entity.Localizacao;
import bpmlab.shift.entity.MetodoDeTrituracao;
import bpmlab.shift.entity.Nutriente;
import bpmlab.shift.entity.Papel;
import bpmlab.shift.entity.TipoEmbalagem;
import bpmlab.shift.entity.Usuario;
import javax.persistence.EntityManager;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * Web application lifecycle listener.
 *
 * @author Mikael Lima
 */
@WebListener
public class BootStrap implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        JpaUtil.init();

        Usuario usuario = new Usuario("Mikael Lima", "mkmikael", "123");
        Papel papel = new Papel("ROLE_ADMIN");
        usuario.getPapeis().add(papel);

        Cardapio cardapio = new Cardapio("Feijoada");
        Item item = new Item("Feijão");
        cardapio.getItens().add(item);
        item.getCardapios().add(cardapio);

        Localizacao localizacao = new Localizacao("Barcarena", null);
        MetodoDeTrituracao mdt = new MetodoDeTrituracao("Liquidificador", "");
        Aplicacao aplicacao = new Aplicacao("Boi", "");
        Equipamento equipamento = new Equipamento("Martelo", "");
        TipoEmbalagem tipoEmbalagem = new TipoEmbalagem("Plástico", "", 10);
        Nutriente nutriente = new Nutriente("A", "");

        salvarTodos(usuario, papel, cardapio, item, mdt, aplicacao, equipamento, tipoEmbalagem, nutriente, localizacao);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

    private void salvarTodos(Object... objects) {
        EntityManager manager = JpaUtil.getEntityManager();
        manager.getTransaction().begin();
        for (Object o : objects) {
            manager.persist(o);
        }
        manager.getTransaction().commit();
        JpaUtil.closeEntityManager();
    }

}
